package com.sentinel.demo.config;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@ResponseBody
public class GlobalDefaultExceptionHandler {
    protected final Logger logger = LoggerFactory.getLogger(GlobalDefaultExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public String exceptionHandler(HttpServletRequest request, Exception e) {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String contextPath = request.getContextPath();
        // 其余异常简单返回为服务器异常
        logger.error("【进入 全局异常 请求路径URI： {} 请求方式： {}  请求contextPath：{}】", requestURI, method, contextPath, e);
        return "异常";
    }

    @ExceptionHandler(value = BlockException.class)
    public String blockExceptionHandler(HttpServletRequest request,BlockException blockException) {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String contextPath = request.getContextPath();
        logger.error("【进入 全局异常 请求路径URI： {} 请求方式： {}  请求contextPath：{}】", requestURI, method, contextPath, blockException);
        return "请求过于频繁";
    }
}